package com.ccit.springbootlaw.controller;

import com.ccit.springbootlaw.pojo.Case;
import com.ccit.springbootlaw.pojo.CaseLawRelationship;
import com.ccit.springbootlaw.service.CaseLawRelationshipService;
import com.ccit.springbootlaw.service.CaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 法律与案件关系控制器
 * 提供根据法律ID查找相关案件的功能
 */
@RestController
@RequestMapping("/api/law-case")
public class LawCaseController {

    @Autowired
    private CaseLawRelationshipService caseLawRelationshipService;

    @Autowired
    private CaseService caseService;

    /**
     * 根据法律ID查找相关案件
     *
     * @param lawId 法律ID
     * @return 返回与该法律相关的案件列表
     */
    @GetMapping("/{lawId}")
    public List<Case> findCasesByLawId(@PathVariable int lawId) {
        // 根据法律ID查找法律与案件的关系
        List<CaseLawRelationship> relationships = caseLawRelationshipService.findByLawId(lawId);

        // 提取案件ID列表
        List<Integer> caseIds = relationships.stream()
                .map(CaseLawRelationship::getCaseId)
                .collect(Collectors.toList());

        // 创建一个空的案件列表用于存储查询结果
        List<Case> cases = new ArrayList<>();

        // 遍历案件ID列表，逐个查询案件信息并添加到列表中
        for (Integer caseId : caseIds) {
            Case caseInfo = caseService.findById(caseId);
            if (caseInfo != null) {
                cases.add(caseInfo);
            }
        }

        // 返回查询到的案件列表
        return cases;
    }
}